﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MengLin.OOP.DesignPattern.Singleton
{
    public class Singleton
    {
        private static readonly object Singleton_Lock = new object();

       //2、使用静态全局变量保存唯一的实例
        private static Singleton _singleton;

        //1、首先将构造函数声明成私有类型，屏蔽通过直接实例化的形式访问
        private Singleton()
        {
            Console.WriteLine("构造函数只被执行一次");
        }

        //3、这里保证只实例化1次，也就是第一次进行实例化，接下来继续调用不会实例化
        public static Singleton CreateInstance1()
        {
            if (_singleton == null)
            { 
                lock (Singleton_Lock)
                {
                    if (_singleton == null)
                    {
                        _singleton = new Singleton();
                    }
                }
            }

            return _singleton;
        }

        /// <summary>
        /// 控制不住多线程
        /// </summary>
        /// <returns></returns>
        public static Singleton CreateInstance2()
        {
            if (_singleton == null)
            {
                _singleton = new Singleton();
            }

            return _singleton;
        }
    }
}
